<script setup lang="ts">
import { ref, defineProps, defineEmits, reactive } from 'vue'
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElMessage,
  ElDatePicker,
  ElSelect,
  ElOption
} from 'element-plus'
import { SUCCESS_CODE } from '@/constants'
import type { FormInstance, FormRules } from 'element-plus'
import { createTaskApi, getTaskApi, updateTaskApi } from '@/api/task'
import { useUserStore } from '@/store/modules/user'
import { formatToDateTime } from '@/utils/dateUtil'

interface Props {
  type: string //角色管理创建用户时传递的参数，如果有saleType字段会覆盖data.type = 'buyer' || 'seller'
  taskUuid: string
}

interface Emit {
  (e: 'handleTask'): void
}

const props = defineProps<Props>()

const emit = defineEmits<Emit>()

const visible = defineModel({ required: true, type: Boolean })

const title = props.type === 'add' ? '添加任务' : '编辑任务'

const userStore = useUserStore()

const formRef = ref<FormInstance>()
const model = ref({
  uuid: null,
  name: null,
  status: '',
  end_time: '',
  remark: null,
  user_id: null
})

const rules = reactive<FormRules>({
  name: [
    {
      required: true,
      message: '请输入姓名',
      trigger: ['input', 'blur']
    }
  ],
  end_time: [
    {
      required: true,
      message: '请输入选择截止日期',
      trigger: ['input', 'blur']
    }
  ]
})

const loading = ref(false)

function handleCancel() {
  visible.value = false
}
const initTask = async () => {
  console.log(props.type)
  console.log(props.taskUuid)
  if (props.type === 'edit') {
    const res = await getTaskApi({ uuid: props.taskUuid })
    if (res) {
      model.value = res.retObj
      console.log(model.value)
      model.value.status = model.value.status
    }
  }
}
initTask()

async function handleAjax() {
  try {
    if (props.type === 'add') {
      const data = JSON.parse(JSON.stringify(model.value))
      data.status = '0'
      data.user_id = userStore.getUserInfo.user.uuid
      data.create_by = userStore.getUserInfo.user.name
      data.update_by = userStore.getUserInfo.user.name
      data.end_time = formatToDateTime(model.value.end_time)
      delete data.uuid
      const response = await createTaskApi(data)
      if (response.code === SUCCESS_CODE) {
        emit('handleTask')
        ElMessage.success('任务添加成功')
        handleCancel()
      }
    } else {
      const data = JSON.parse(JSON.stringify(model.value))
      data.user_id = userStore.getUserInfo.user.uuid
      data.create_by = userStore.getUserInfo.user.name
      data.update_by = userStore.getUserInfo.user.name
      data.end_time = formatToDateTime(model.value.end_time)
      const response = await updateTaskApi(data)
      if (response.code === SUCCESS_CODE) {
        emit('handleTask')
        ElMessage.success('任务修改成功')
        handleCancel()
      }
    }

    loading.value = false
  } catch (error: any) {
    ElMessage.error(error.msg)
    loading.value = false
  }
}

async function handleSubmit(formEl: FormInstance | undefined) {
  loading.value = true
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    loading.value = false
    if (valid) {
      handleAjax()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const handleOpen = () => {
  formRef.value?.resetFields()
}
</script>

<template>
  <ElDialog
    v-model="visible"
    :auto-focus="false"
    :title="title"
    preset="card"
    style="width: 95%; max-width: 640px"
    @open="handleOpen"
  >
    <ElForm
      ref="formRef"
      :model="model"
      :rules="rules"
      label-placement="left"
      label-width="auto"
      :style="{ padding: '0px 20px' }"
    >
      <ElFormItem prop="name" label="任务名称">
        <ElInput v-model="model.name" clearable :placeholder="'请输入任务名称'" />
      </ElFormItem>
      <ElFormItem v-if="props.type === 'edit'" prop="status" label="状态">
        <ElSelect v-model="model.status" placeholder="请选择状态" clearable>
          <el-option label="未完成" value="0" />
          <el-option label="已完成" value="1" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem prop="end_time" label="截止日期">
        <ElDatePicker
          v-model="model.end_time"
          type="datetime"
          placeholder="请输入截止日期"
          format="YYYY-MM-DD HH:mm:ss"
          date-format="YYYY-MM-DD"
          time-format="HH:mm:ss"
        />
      </ElFormItem>
      <ElFormItem prop="remark" label="描述">
        <ElInput v-model="model.remark" type="textarea" :rows="4" placeholder="请输入描述信息" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel"> 取消 </el-button>
        <el-button type="primary" @click="handleSubmit(formRef)"> 确定 </el-button>
      </div>
    </template>
  </ElDialog>
</template>
